package com.hanamaki.unit.junit.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 工具类
 */
public class JDBCUtil {

    static DataSource dataSource;
    static Connection connection;
    static Statement statement;
    static ResultSet resultSet;
    static ResultSetMetaData metaData;
    static{
        dataSource = new ComboPooledDataSource("MySources");
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static Object[][] getSqlContent(String tableName) {
        Object[][] result = null;
        // 创建 执行sql语句的对象
        try {
            statement = connection.createStatement();
            // 编写sql
            String sql = "select * from " + tableName;
            // 执行查询
            resultSet = statement.executeQuery(sql);
            //获取表的结果 行 列
            metaData = resultSet.getMetaData();
            // 获取表中的列数
            int columnCount = metaData.getColumnCount();
            // 定义一个 存取 每一行的值的集合
            List<Object[]> list = new ArrayList<>();
            // 循环取值
            while (resultSet.next()) {
                // 定义 长度 为 columnCount 的数组
                String[] content = new String[columnCount];
                for (int i = 0; i < columnCount; i++) {
                    // 将循环 去除的某一行 存到数组中  再存到集合中
                    content[i] = resultSet.getString(i + 1);
                }
                list.add(content);
            }
            // 定义一个二维数组
            result = new Object[list.size()][];
            for (int i = 0; i < list.size(); i++) {
                result[i] = list.get(i);
            }

        } catch (Exception throwables) {
            throwables.printStackTrace();
        }finally {
            release(connection, resultSet, statement, null);
        }

        return result;
    }

    public static void release(Connection connection, ResultSet resultSet, Statement statement, PreparedStatement preparedStatement) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}
